import React from 'react'
import { useInitialized } from '../hooks/use-initialized'

interface Props {
  /** active 是否渲染 */
  active: boolean
  /** 是否关闭销毁 */
  destroyOnClose?: boolean
  /** 是否强制渲染 */
  forceRender?: boolean
  /** children */
  children: React.ReactElement
}

/**
 * @description - 子组件是否渲染
 * @returns {boolean}
 */
export function useShouldRender(
  active: boolean,
  destroyOnClose?: boolean,
  forceRender?: boolean,
): boolean {
  const initialized = useInitialized(active)
  if (forceRender) return true
  if (active) return true
  if (!initialized) return false
  return !destroyOnClose
}

export const ShouldRender: React.FC<Props> = (props) => {
  const {
    active,
    destroyOnClose,
    forceRender,
    children,
  } = props

  const shouldRender = useShouldRender(
    active,
    destroyOnClose,
    forceRender,
  )

  return shouldRender ? children : null
}
